<?php

namespace app\api\controller;

use addons\zpwxsys\model\Company as CompanyModel;
use addons\zpwxsys\model\User as UserModel;
use addons\zpwxsys\service\Token;
use app\common\controller\Api;
use app\common\model\ChatConversations;
use app\common\model\ChatMessages;
use think\Db;

class Chat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 发送消息
     * 发送者类型 sender_type 1-求职者，2-企业
     * 消息类型 message_type 1-文本，2-图片，3-文件  ，4-查询消息记录
     */
    public function send()
    {
        $post = $this->request->post();
        if ($post['sender_type'] == 1) {
            $job_seeker_id = Token::getCurrentUid();
            $post['sender_id'] = $job_seeker_id;
            $where['job_seeker_id'] = $job_seeker_id;
            $where['enterprise_id'] = $post['enterprise_id'];
            $where['del_time'] = 0;
        } else if ($post['sender_type'] == 2) {
            $enterprise_id = Token::getCurrentCid($post['ctoken']);
            $post['sender_id'] = $enterprise_id;
            $where['job_seeker_id'] = $post['job_seeker_id'];
            $where['enterprise_id'] = $enterprise_id;
            $where['del_time'] = 0;
        }
        $conversations = ChatConversations::where($where)->find();
        if (!$conversations) {
            $data = [
                'job_seeker_id' => $post['job_seeker_id'],
                'enterprise_id' => $post['enterprise_id'],
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time(),
                'del_time' => 0,
            ];
            $conversations = ChatConversations::create($data);
        }
        $meg = [
            'conversation_id' => $conversations['id'],
            'sender_type' => $post['sender_type'],
            'sender_id' => $post['sender_id'],
            'is_read' => 0,
            'is_recalled' => 0,
            'createtime' => time(),
            'updatetime' => time(),
        ];
        if ($post['message_type'] == 1) {
            $meg['content'] = $post['content'];
            $meg['message_type'] = $post['message_type'];
            $meg['file_url'] = $post['file_url'];
            $meg['file_size'] = 0;
        } elseif ($post['message_type'] == 2) {
            $meg['content'] = $post['content'];
            $meg['message_type'] = $post['message_type'];
            $meg['file_url'] = $post['file_url'];
            $attachment = Db::name('attachment')->where('url', $post['file_url'])->find();
            $meg['file_name'] = $attachment['filename'];
            $meg['file_size'] = $attachment['filesize'];
        } elseif ($post['message_type'] == 3) {
            $meg['content'] = $post['content'];
            $meg['message_type'] = $post['message_type'];
            $meg['file_url'] = $post['file_url'];
            $attachment = Db::name('attachment')->where('url', $post['file_url'])->find();
            $meg['file_name'] = $attachment['filename'];
            $meg['file_size'] = $attachment['filesize'];
        }
        if ($post['message_type'] != 4) {
            $messages = ChatMessages::create($meg);
            if ($post['sender_type'] == 1) {
                ChatMessages::where(['conversation_id' => $conversations['id'], 'sender_type' => 2, 'is_read' => 0])->update(['is_read' => 1, 'updatetime' => time()]);
                $upda = [
                    'last_message_id' => $messages['id'],
                    'last_message_time' => date('Y-m-d H:i:s'),
                    'job_seeker_unread' => 0,
                    'enterprise_unread' => ChatMessages::where(['conversation_id' => $conversations['id'], 'sender_type' => 1, 'is_read' => 0])->count(),
                    'updatetime' => time()
                ];
            } else {
                ChatMessages::where(['conversation_id' => $conversations['id'], 'sender_type' => 1, 'is_read' => 0])->update(['is_read' => 1, 'updatetime' => time()]);
                $upda = [
                    'last_message_id' => $messages['id'],
                    'last_message_time' => date('Y-m-d H:i:s'),
                    'job_seeker_unread' => ChatMessages::where(['conversation_id' => $conversations['id'], 'sender_type' => 2, 'is_read' => 0])->count(),
                    'enterprise_unread' => 0,
                    'updatetime' => time()
                ];
            }
            ChatConversations::where('id', $conversations['id'])->update($upda);
        } else {
            $messages = 1;
        }

        if ($messages) {
            $res = Db::name('chat_conversations')->where($where)->find();
            $userinfo = UserModel::getByUserWhere(['id' => $res['job_seeker_id']]);
            $companyinfo = CompanyModel::getCompany($res['enterprise_id']);
            $res['history'] = Db::name('chat_messages')->where(['conversation_id' => $conversations['id']])->order('createtime')->select();

            foreach ($res['history'] as $k => $v) {
                $res['history'][$k]['is_current'] = 0;
                if($v['message_type']==2||$v['message_type']==3){
                    $res['history'][$k]['file_url'] = cdnurl($v['file_url'], true);
                }
                if ($v['sender_type'] == 1) {
                    if ($post['sender_type'] == 1) {
                        $res['history'][$k]['is_current'] = 1;
                    }
                    $res['history'][$k]['nickname'] = $userinfo['nickname'];
                    $res['history'][$k]['avatarUrl'] = $userinfo['avatarUrl'];
                } else {
                    if ($post['sender_type'] == 2) {
                        $res['history'][$k]['is_current'] = 1;
                    }
                    $res['history'][$k]['nickname'] = $companyinfo['companyname'];
                    $res['history'][$k]['avatarUrl'] = $companyinfo['thumb'];
                }
            }

            if ($post['message_type'] != 4) {
                $this->success(__('发送成功'), $res);
            } else {
                $this->success(__('成功'), $res);
            }

        } else {
            $this->error(__('发送失败'));
        }

    }

    /**
     * 消息列表
     */
    public function msglist()
    {
        $post = $this->request->post();
        $page = $post['page'] ? $post['page'] : 1;
//        $limit = $post['limit'] ? $post['limit'] : 9999;
        $limit = 9999;
        if (isset($post['ctoken']) && $post['ctoken'] != '') {
            $enterprise_id = Token::getCurrentCid($post['ctoken']);

            $order = 'job_seeker_unread desc';
            $where['enterprise_id'] = $enterprise_id;
            $where['del_time'] = 0;
        } else {
            $job_seeker_id = Token::getCurrentUid();
            $order = 'enterprise_unread desc';
            $where['job_seeker_id'] = $job_seeker_id;
            $where['del_time'] = 0;
        }
        $res = Db::name('chat_conversations')->where($where)->order($order)->paginate($limit, false, ['page' => $page])->toArray();
        foreach ($res['data'] as &$v) {
            $v['messages'] = Db::name('chat_messages')->where(['conversation_id' => $v['id']])->order('createtime desc')->find();
            if (isset($post['ctoken']) && $post['ctoken'] != '') {
                $userinfo = UserModel::getByUserWhere(['id' => $v['job_seeker_id']]);
                $v['nickname'] = $userinfo['nickname'];
                $v['avatarUrl'] = $userinfo['avatarUrl'];
            } else {
                $companyinfo = CompanyModel::getCompany($v['enterprise_id']);
                $v['nickname'] = $companyinfo['companyname'];
                $v['avatarUrl'] = $companyinfo['thumb'];
            }
        }
        $this->success(__('成功'), $res);
    }

    /**
     * 删除消息
     */
    public function del(){
        $post = $this->request->post();
        $where['id'] = $post['id'];
        $where['del_time'] = 0;
        $res = Db::name('chat_conversations')->where($where)->update(['del_time'=>time()]);
        if($res){
            $this->success(__('删除成功'));
        }else{
            $this->error(__('删除失败'));
        }
    }

    /**
     * 消息已读
     */
    public function read()
    {
        $post = $this->request->post();
        if (isset($post['ctoken']) && $post['ctoken'] != '') {
            $where['conversation_id'] = $post['id'];
            $where['sender_type'] = 1;
            $where['is_read'] = 0;
        } else {
            $where['conversation_id'] = $post['id'];
            $where['sender_type'] = 2;
            $where['is_read'] = 0;
        }
        $messages = Db::name('chat_messages')->where($where)->update(['is_read' => 1, 'updatetime' => time()]);
        if($messages){
            $this->success(__('成功'), $messages);
        }else{
            $this->error(__('失败'));
        }

    }


    /**
     * 简历收藏
     */
    public function collect(){
        $post = $this->request->post();
        $job_seeker_id = Token::getCurrentCid($post['ctoken']);
        $res = Db::name('collect_notes')->where(['jobid'=>$job_seeker_id,'note_id'=>$post['note_id']])->find();
        if($post['type']==1){
            if($res){
                $this->error(__('已收藏'));
            }else{
                $data = [
                    'jobid'=>$job_seeker_id,
                    'note_id'=>$post['note_id'],
                    'createtime'=>time()
                ];
                $res = Db::name('collect_notes')->insert($data);
                if($res){
                    $this->success(__('收藏成功'));
                }else{
                    $this->error(__('收藏失败'));
                }
            }
        }else{
            if($res){
                $data = Db::name('collect_notes')->where('id',$res['id'])->delete();
                if($data){
                    $this->success(__('取消收藏成功'));
                }else{
                    $this->error(__('取消收藏失败'));
                }
            }else{
                $this->error(__('未收藏'));
            }
        }

    }

}
